<template>
  <van-nav-bar
    :title="`测评详情`"
    left-text="返回"
    left-arrow
    @click-left="onClickLeft"
  />

  <div v-if="curTopic" v-swipe="handleSwipe" class="content">
    <van-row class="progress">
      <div class="left">
        <b>{{ (curIndex + 1 + '').padStart(2, '0') }}</b
        >/{{ topicList.length }}
      </div>
      <van-progress
        class="van-progress"
        :show-pivot="false"
        color="#0387cf"
        :percentage="((curIndex + 1) / topicList.length) * 100"
      />
    </van-row>

    <van-swipe class="my-swipe" :show-indicators="false" :loop="false">
      <van-swipe-item>
        <div class="levels">
          <div class="topic">
            {{ curTopic?.subjecName }}
          </div>

          <ul
            v-if="curTopic.type === 1 || curTopic.type === -1"
            class="options"
          >
            <li
              v-for="item of options"
              :key="item.answer"
              :class="{ active: getActive(item) }"
              @click="onItemClick(item, curTopic)"
            >
              {{ item.answer }}
            </li>
          </ul>

          <div v-if="curTopic.type === 2" class="input">
            <van-field
              v-model="options[0].answer"
              label="填空题"
              placeholder="请输入"
            />
            <van-button
              plain
              type="primary"
              block
              @click="onItemClick(options[0], curTopic)"
            >
              确认
            </van-button>
          </div>
        </div>
      </van-swipe-item>
    </van-swipe>

    <div class="bottom-wrapper">
      <van-button size="small" type="primary" round @click="handleClickPre">
        上一题
      </van-button>
      <van-button size="small" type="primary" round @click="handleClickNext">
        下一题
      </van-button>
    </div>
    <van-dialog
      v-model:show="show"
      :cancel="cancel"
      :before-close="beforeClose"
      :confirm="dialogSubmit"
      title="恭喜你,完成所有问题,"
      message="是否提交结果?"
      cancel-button-text="返回修改"
      confirm-button-text="确认提交"
      show-cancel-button
    ></van-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, defineProps, Ref, ref, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from '/@/store'
import { useBack } from '/@/use/useRouteBack'
import { Dialog, Toast } from 'vant'
import dayjs, { Dayjs } from 'dayjs'
import { submitTopics } from '/@/api/evaluate/topics'
import { ajax } from './utils/ajax'
import { useTopics, useSubmit, useJump, useItem, useTime } from './useDetails'

const props = defineProps<{ stage: string; projectId: string }>()

const { projectId } = toRefs(props)

const answerList = ref<any[]>([])

const { state } = useStore()

const userInfo = computed(() => state.userInfo)

const router = useRouter()

const { curIndex, curTopic, options, topicList, isCompleted } =
  useTopics(projectId)

const show = ref(false)

// const { handleSubmit } = useSubmit({
//   answerList,
//   projectId,
//   userInfo,
//   handleAfterSubmit({ data, code, msg }) {
//     console.log(data)

//     if (code == 400) {
//       Dialog.alert(msg)
//       return
//     }

//     router.push({
//       name: 'EvaluateResult',
//       query: { userProjectId: data.userProjectId },
//     })
//   },
//   Dialog,
// })

// const { handleSubmit } = submit({
//   answerList,
//   projectId,
//   userInfo,
//   handleAfterSubmit({ data, code, msg }) {
//     console.log(data)

//     if (code == 400) {
//       Dialog.alert(msg)
//       return
//     }

//     router.push({
//       name: 'EvaluateResult',
//       query: { userProjectId: data.userProjectId },
//     })
//   },
//   Dialog,
// })

function handleSubmit() {}

const { nextDisabled, handleSwipe, handleClickPre, handleClickNext } = useJump({
  answerList,
  curIndex,
  isCompleted,
  handleSubmit,
  Toast,
  show,
})

const { onItemClick, getActive } = useItem({
  answerList,
  curIndex,
  isCompleted,
  projectId,
  handleSubmit,
  show,
})

const { back: onClickLeft } = useBack()

function dialogSubmit() {
  show.value = false
}

function cancel() {
  show.value = false
}

const { startTime, endTime, duration, getTime } = useTime()

function handleAfterSubmit({ data, code, msg }: Record<any, any>) {
  if (code == 400) {
    Dialog.alert(msg)
    return
  }

  router.push({
    name: 'EvaluateResult',
    query: { userProjectId: data.userProjectId },
  })
}

async function beforeClose(action: string) {
  if (action != 'confirm') {
    return true
  }

  getTime()
  const datas: any[] = answerList.value
  const { gradeId, classNo, sexName, tenantName, account } = userInfo.value

  const userProjectGaugeEntity = {
    projectId: projectId.value,
    startTime: startTime.value.format('YYYY-MM-DD HH:mm:ss'),
    endTime: endTime.value.format('YYYY-MM-DD HH:mm:ss'),
    duration: duration.value,
    gradeId,
    classNo,
    sex: sexName,
    schoolName: tenantName,
    userName: account,
  }

  await ajax({
    datas,
    userProjectGaugeEntity,
  })
    .then((res: any) => {
      handleAfterSubmit?.(res.data)
    })
    .catch((error) => {
      console.error(error)
      return true
    })

  return true
}

function submit({
  answerList,
  projectId,
  userInfo,
  handleAfterSubmit,
  Dialog,
}: {
  answerList: Ref<any[]>
  projectId: Ref<string>
  userInfo: Ref<any>
  handleAfterSubmit?: (data: any) => void
  Dialog: any
}) {
  const { startTime, endTime, duration, getTime } = useTime()

  return {
    handleSubmit() {
      return Dialog.confirm({
        title: '恭喜你,完成所有问题,',
        message: '是否提交结果?',
        cancelButtonText: '返回修改',
        confirmButtonText: '确认提交',
        async beforeClose(action: string) {
          if (action != 'confirm') {
            return true
          }

          getTime()
          const datas: any[] = answerList.value
          const { gradeId, classNo, sexName, tenantName, account } =
            userInfo.value

          const userProjectGaugeEntity = {
            projectId: projectId.value,
            startTime: startTime.value.format('YYYY-MM-DD HH:mm:ss'),
            endTime: endTime.value.format('YYYY-MM-DD HH:mm:ss'),
            duration: duration.value,
            gradeId,
            classNo,
            sex: sexName,
            schoolName: tenantName,
            userName: account,
          }

          await ajax({
            datas,
            userProjectGaugeEntity,
          })
            .then((res: any) => {
              handleAfterSubmit?.(res.data)
            })
            .catch((error) => {
              console.error(error)
              return true
            })

          return true
        },
      })
    },
  }
}
</script>

<style lang="less" scoped>
.content {
  padding: 36px 37.5px;
  height: 90vh;
}
.progress {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 10px;
  .left {
    margin-right: 8px;

    font-size: 12px;
    b {
      font-weight: 700;
      font-size: 18px;
      color: #0387cf;
    }
  }
  .van-progress {
    flex: 1;
    // width: 100%;
  }
  .right {
    margin-left: 8px;
    font-size: 12px;
    color: #999;
    & > * {
      margin-right: 3px;
    }
  }
}

.topic {
  font-size: 18px;
  margin-bottom: 30px;
  color: #505050;
  min-height: 48px;
}

.options {
  font-size: 15px;
  max-height: calc(100vh - 300px);
  overflow-y: scroll;

  li {
    width: 100%;
    background: #e6ebee;
    border-radius: 3px;
    margin-bottom: 20px;
    // padding: 12px;
    padding-left: 30px;
    height: 35px;
    line-height: 18px;
    color: #595757;
    text-align: left;
    display: flex;
    align-items: center;
    /deep/ .van-button__content {
      justify-content: left;
    }
    position: relative;
    &:before {
      content: '';
      position: absolute;
      margin-right: 10px;
      width: 15px;
      height: 15px;
      top: 50%;
      left: 10px;
      margin-top: -7.5px;
      border-radius: 50%;
      background: #ffffff;
      border: 1px solid #c6cbcb;
      box-sizing: border-box;
      display: block;
    }
    &.active {
      background: #c0e6fa;
      color: #3071b9;
      &:before {
        background: #3071b9;
        border-color: #3071b9;
      }
    }
  }

  /deep/ .van-button:before {
    background-color: #1989fa !important;
  }
}

.van-icon-arrow-left {
  position: fixed;
  top: 50%;
  left: 4px;
}

.van-icon-arrow {
  position: fixed;
  top: 50%;
  right: 4px;
}

.bottom-wrapper {
  position: fixed;
  bottom: 60px;
  display: flex;
  justify-content: space-between;
  left: 0;
  right: 0;
  padding: 0 40px;
  /deep/ .van-button {
    padding: 0 40px;
  }
}
</style>
